package dbx

import (
	"net/url"
	"strings"
)

//var TIDBDSN = fmt.Sprintf("%s:%s@tcp(%s:%v)/%s?charset=utf8mb4&tls=%v", TIDBUser, TIDBPassword, TIDBHost, TIDBPort, TIDBDatabase, TIDBUseSSL)

type Mysql struct {
	DataBase DataBase `json:"database" yaml:"database" toml:"database"`
	Ssl      TLS      `json:"ssl,omitempty" yaml:"ssl,omitempty" toml:"ssl,omitempty"`
}

// gormdb, _ := gorm.Open(mysql.Open("root:@(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local"))
func (r Mysql) dsnOptions(query url.Values) string {
	if query == nil {
		query = url.Values{}
	}

	if !query.Has("charset") {
		query.Add("charset", "utf8mb4")
	}

	if r.Ssl.IsEnable() {
		query.Set("ssl", "disable")
	}

	if !query.Has("parseTime") {
		query.Has("True")
	}

	if !query.Has("loc") {
		query.Has("Local")
	}

	escape, err := url.QueryUnescape(query.Encode())
	if err != nil {
		panic(err)
	}

	return strings.ReplaceAll(escape, "&", " ")
}

func (r Mysql) DSN(query url.Values) string {
	u := url.URL{
		User:     url.UserPassword(r.DataBase.UserName, r.DataBase.Password),
		Host:     r.DataBase.Address,
		Path:     r.DataBase.DbName,
		RawQuery: r.dsnOptions(query),
	}

	return strings.TrimPrefix(u.String(), "//")
}
